package com.zt.weibo.main;

import android.content.Context;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.PopupWindow;

import com.zt.weibo.R;
import com.zt.weibo.utils.AsyncImageLoader;
import com.zt.weibo.utils.PrintLog;

/**
 * 该类用于弹窗显示微博图片。
 * @author zhaotong
 */
public class WeiboImgPopwin
{
	private PopupWindow mPopWin = null;
	private Context mContext = null;
	private View mParentView = null;
	private View mContentView = null;
	private ImageView mImg = null;
	private AsyncImageLoader mIconLoader = null;
	
	public WeiboImgPopwin(Context con, View parentView)
	{
		mContext = con;
		mParentView = parentView;
		mContentView = LayoutInflater.from(mContext).inflate(R.layout.weibo_img_popwin, null);
		mPopWin = new PopupWindow(mContentView, LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
		mPopWin.setFocusable(true);
		mPopWin.setOutsideTouchable(false);
		mPopWin.setAnimationStyle(R.style.popwin_animation);
		mImg = (ImageView) mContentView.findViewById(R.id.weibo_big_img);
		mIconLoader = AsyncImageLoader.getInstance();
		setListeners();
	}
	
	/**
	 * 根据网址显示图片。
	 * @param strOriginalPic
	 */
	public void show(String strOriginalPic)
	{
		PrintLog.debug(strOriginalPic);
		try
		{
			mPopWin.showAtLocation(mParentView, Gravity.CENTER, 0, 0);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		mImg.setImageResource(R.drawable.icon);
		mIconLoader.loadImage(strOriginalPic, mImg);
	}
	
	private void dismiss()
	{
		try
		{
			if(null != mPopWin && mPopWin.isShowing())
			{
				mPopWin.dismiss();
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}
	
	private void setListeners()
	{
		TouchListener touchListener = new TouchListener();
		KeyListener keyListener = new KeyListener();
		mContentView.setOnKeyListener(keyListener);
		mContentView.setOnTouchListener(touchListener);
	}
	
	private class TouchListener implements OnTouchListener
	{
		@Override
		public boolean onTouch(View v, MotionEvent event)
		{
			dismiss();
			return false;
		}
	}
	
	private class KeyListener implements OnKeyListener
	{
		@Override
		public boolean onKey(View v, int keyCode, KeyEvent event)
		{
			if (keyCode == KeyEvent.KEYCODE_BACK)
			{
				dismiss();
			}
			return true;
		}
	}
	
}
